/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package iamutkarshtiwari.github.io.imageeditorsample;

import com.muddzdev.styleabletoast.styleabletoast.StyleableToast;
import iamutkarshtiwari.github.io.ananas.editimage.EditImageAbility;
import iamutkarshtiwari.github.io.ananas.editimage.utils.*;
import iamutkarshtiwari.github.io.imageeditorsample.ability.TakePictureAbility;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextTool;
import ohos.agp.window.service.Window;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;

/**
 * 媒体库
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private final static String TAG = MainAbilitySlice.class.getSimpleName();
    private final static int SELECT_FROM_ABLUM = 1001;
    private static final int ACTION_REQUEST_EDITIMAGE = 9;
    private static final int TAKE_PICTURE_CODE = 666;

    private Image take_img;
    private String sourceFilePath;
    private String picturePath;

    @Override
    public void onStart(Intent intent) {
        Window window = getWindow();
        window.setStatusBarColor(Color.getIntColor("#757575"));
        window.setStatusBarVisibility(Component.VISIBLE);
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        take_img = (Image) findComponentById(ResourceTable.Id_img);
        findComponentById(ResourceTable.Id_select_album).setClickedListener(this);  //拍照
        findComponentById(ResourceTable.Id_take_photo).setClickedListener(this);    //图库
        findComponentById(ResourceTable.Id_edit_image).setClickedListener(this);    //编辑
        File dir = getExternalFilesDir("Pictures" + File.separator + "xinlanedit");
        if (!dir.exists()) {
            if (dir.mkdir()) {
                LogUtil.loge("File dir true");
            }
        }
        picturePath = dir + File.separator;
    }

    @Override
    public void onActive() {
        super.onActive();

    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();

        if (id == ResourceTable.Id_take_photo) {
            takePhotoClick();
        } else if (id == ResourceTable.Id_edit_image) {
            editImageClick();
        } else if (id == ResourceTable.Id_select_album) {
            selectFromAblum();
        }
    }

    protected void takePhotoClick() {
        PermissionUtils.getCameraPermission(new String[]{"ohos.permission.CAMERA"}, getAbility());


        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(TakePictureAbility.class.getName())
                .build();

        Intent intent = new Intent();
        intent.setOperation(operation);
        startAbilityForResult(intent, TAKE_PICTURE_CODE);
    }

    private void editImageClick() {
        EditImageAbility editImageAbility = new EditImageAbility();
        editImageAbility.setMainBit(take_img.getPixelMap());

        if (null == take_img.getPixelMap()) {
            new StyleableToast
                    .Builder(getContext())
                    .text("Please choose an image for edit")
                    .textColor(Color.BLACK)
                    .textSize(14)
                    .backgroundColor(new Color(0xF0F0F0))
                    .cornerRadius(19)
                    .show();
            return;
        }
        String outputFile = genEditFile();
        Intent intent = new Intent();
        intent.setParam("SourceFilePath", sourceFilePath);
        intent.setParam("OutputFilePath", outputFile);
        presentForResult(editImageAbility, intent, ACTION_REQUEST_EDITIMAGE);
    }

    private String genEditFile() {
        if (TextTool.isNullOrEmpty(sourceFilePath)) {
            return "";
        }
        String path = picturePath;//getCacheDir().getAbsolutePath() + "/";    //目前仅有权限操作app cache目录下的文件
        String filename = sourceFilePath.substring(sourceFilePath.lastIndexOf(File.separator) + 1);
        String[] str = filename.split("\\.");
        String newName = "tietu" + System.currentTimeMillis() + "." + str[1];
        return path + newName;  //输出路径
    }

    private void selectFromAblum() {
        Operation operation = new Intent.OperationBuilder()
                .withAction("android.intent.action.PICK")
                .build();

        Intent intent = new Intent();
        intent.setOperation(operation);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent, SELECT_FROM_ABLUM);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        if (requestCode == SELECT_FROM_ABLUM) {
            getPictureFromAblum(requestCode, resultCode, resultData);
        } else if (requestCode == TAKE_PICTURE_CODE) {
            getPictureFromCamera(resultData);
        }
    }

    @Override
    protected void onResult(int requestCode, Intent resultData) {
        if (requestCode == ACTION_REQUEST_EDITIMAGE) {
            handleEditorImage(resultData);
        }
    }

    private void getPictureFromCamera(Intent resultData) {
        if (resultData != null) {
            String filePath = resultData.getStringParam(TakePictureAbility.TAKE_PICTURE);
            getUITaskDispatcher().asyncDispatch(() -> {
                take_img.setPixelMap(BitmapUtils.getPixMapFromPath(filePath));
                sourceFilePath = filePath;
            });
        }
    }

    private void getPictureFromAblum(int requestCode, int resultCode, Intent resultData) {
        PixelMap pixelMap = null;
        if (requestCode == 1001 && resultCode == -1 && null != resultData) {
            ohos.utils.net.Uri uri = resultData.getUri();

            if (null != uri) {
                String mediaId = getNumbers(uri.toString());
                Uri mediaUri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, mediaId);
                try {
                    DataAbilityHelper helper = DataAbilityHelper.creator(getContext());
                    ResultSet resultSet = helper.query(mediaUri, null, null);

                    while (resultSet.goToNextRow()) {
                        //路径
                        String path = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.Video.Media.DATA));
                        //时长
                        long duration = resultSet.getLong(resultSet.getColumnIndexForName(AVStorage.Video.Media.DURATION));
                        //大小
                        long size = resultSet.getLong(resultSet.getColumnIndexForName(AVStorage.Video.Media.SIZE));
                        //名字
                        String displayName = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.Video.Media.DISPLAY_NAME));
                        //类型
                        String mimeType = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.Video.Media.MIME_TYPE));
                        LogUtils.logd(mediaUri + "--" + path + "--" + duration + "--" + size + "--" + displayName + "--" + mimeType);
                        if (mimeType.contains("image")) {
                            pixelMap = BitmapUtils.getPixMapFromUri(mediaUri, getContext());
                            int height = pixelMap.getFitDensitySize(0).height;
                            int width = pixelMap.getFitDensitySize(0).width;

                            LogUtils.logd("pixelMap  height=" + height + "=width=" + width);
                        }
                        sourceFilePath = path;
                    }
                    resultSet.close();

                    take_img.setPixelMap(pixelMap);
                } catch (DataAbilityRemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void handleEditorImage(Intent data) {
        if (data == null) {
            return;
        }

        String newFilePath = data.getStringParam("OutputFilePath");
        boolean isImageEdit = data.getBooleanParam("IS_IMAGE_EDITED", false);

        PixelMap pixelMap = take_img.getPixelMap();
        if (isImageEdit) {
            pixelMap = BitmapUtils.getPixMapFromPath(newFilePath);
            try {
                String string = getResourceManager().getElement(ResourceTable.String_save_path).getString(newFilePath);
                MyToast.show2(getContext(), string);
            } catch (IOException | NotExistException | WrongTypeException e) {
                e.printStackTrace();
            }
        }
        if (null != pixelMap) {
            take_img.setPixelMap(pixelMap);
        }
    }

    public String getNumbers(String content) {
        return content.replaceAll(".*[^\\d](?=(\\d+))", "");
    }
}
